package com.zj.java21demo.filter;

import com.zj.java21demo.entity.TUser;
import com.zj.java21demo.utils.JwtTokenByJdk21Util;
import com.zj.java21demo.utils.ThreadMdcUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;

/**
 * @Version 1.0.0
 * @Date 2024/2/28 17:44
 * @Created by zhangjun
 */
@Slf4j
//@Component
@AllArgsConstructor
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

//    private TokenService tokenService;

    @Resource
    private JwtTokenByJdk21Util jwtTokenByJdk21Util;
    @Resource
    private CustomUserDetailsService customUserDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        if (request.getServletPath().contains("/auth")) {
//            log.debug("URL="+request.getRequestURI()+",不进行校验");
            chain.doFilter(request, response);
            return;
        }

        String token = request.getHeader("Authorization");
        log.debug("======进行Interceptor 校验,URL="+ request.getRequestURI() +"======");
        if(Objects.isNull(token)) {
//            log.debug("URL="+request.getRequestURI()+",token不存在");
            chain.doFilter(request, response);
            return;
        }

        String account = jwtTokenByJdk21Util.extractUsername(token);
        if(Objects.nonNull(account) && Objects.isNull(SecurityContextHolder.getContext().getAuthentication())) {
            UserDetails userDetails = customUserDetailsService.loadUserByUsername(account);
            if(jwtTokenByJdk21Util.isTokenValid(token, userDetails)) {
                log.debug("URL="+request.getRequestURI()+",check security is ok");
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
            chain.doFilter(request, response);
        }

    }

}
